import './index.less'
import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import logo from '../../assets/images/logo.jpg'
import menuList from '../../config/menuConfig'

import { Menu } from 'antd';

const { SubMenu } = Menu;
/*
左侧导航的组件
 */
class LeftNav extends Component {

  // class App extends React.Component {
  //     state = {
  //       collapsed: false,
  //     };

  //     toggleCollapsed = () => {
  //       this.setState({
  //         collapsed: !this.state.collapsed,
  //       });
  //     };


  /*
  根据meun的数据数组生成对应的标签数组
  使用map加递归调用
  */
  getMenuNods = (menuList) => {
    const path = this.props.location.pathname;
    return menuList.map(item => {
      if (!item.children) {
        return (
          <Menu.Item key={item.key} icon={item.icon}>
            <Link to={item.key}>
              <span>{item.title}</span>
            </Link>
          </Menu.Item>
        )
      } else {
        //查找一个与当前路径匹配的item
        const cItem = item.children.find(cItem => cItem.key === path)
        //如果存在，说明当前item的子列表需要打开
        if (cItem) {
          this.openKey = item.key
        }
        return (
          <SubMenu key={item.key} icon={item.icon} title={item.title}>
            {this.getMenuNods(item.children)}
          </SubMenu>

        )
      }
    })

  }

  /*
  在第一次render()之前执行一次
  为第一个render()准备数据(必须同步的) 
  */
  componentWillMount() {
    this.menuNodes = this.getMenuNods(menuList)
  }

  render() {
    //得到当前请求的路由路径
    const path = this.props.location.pathname;
    //得到需要打开的菜单项的key
    const openKey = this.openKey

    return (
      <>
        <div className='left-nav'>
          <Link className='left-nav-header'>
            <img src={logo} alt="" />
            <h1>RNG后台</h1>
          </Link>
        </div>
        <Menu mode="inline" theme="dark" selectedKeys={[path]}>
          {this.menuNodes}
        </Menu>
      </>
    )
  }
}


export default withRouter(LeftNav);
